package com.atguigu.lease.common.config;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.SetBucketPolicyArgs;
import lombok.Data;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConfigurationProperties(prefix = "lease.minio.config")
@Data
public class MinioConfig implements InitializingBean {
    private String endpoint;
    private String accessKey;
    private String secretKey;
    private String bucketName;

    public static String ENDPOINT;
    public static String ACCESS_KEY;
    public static String SECRET_KEY;
    public static String BUCKET_NAME;
    //springioc容器在创建组件对象后 会调用这个方法 完成初始化
    @Override
    public void afterPropertiesSet() throws Exception {
        ENDPOINT = endpoint;
        ACCESS_KEY = accessKey;
        SECRET_KEY = secretKey;
        BUCKET_NAME = bucketName;
    }


    @Bean
    public MinioClient minioClient() throws Exception {
        MinioClient minioClient = MinioClient.builder()
                .endpoint(ENDPOINT) //设置minio服务端地址+端口号
                .credentials(ACCESS_KEY,SECRET_KEY)//设置minio账号和密码
                .build();
        //为了方便桶的使用，在项目启动时 直接初始化桶
        //判断桶是否存在，已存在直接用，不存在才初始化并分配桶的权限
        boolean exists = minioClient.bucketExists(BucketExistsArgs.builder()
                .bucket(BUCKET_NAME)
                .build());
        if(!exists) {
            // 创建桶
            minioClient.makeBucket(MakeBucketArgs.builder()
                    .bucket(BUCKET_NAME)
                    .build());
            //设置公共读的权限
            String config = """
                        {
                          "Statement" : [ {
                            "Action" : "s3:GetObject",
                            "Effect" : "Allow",
                            "Principal" : "*",
                            "Resource" : "arn:aws:s3:::%s/*"
                          } ],
                          "Version" : "2012-10-17"
                        }
                    """.formatted(BUCKET_NAME);
            minioClient.setBucketPolicy(SetBucketPolicyArgs.builder()
                            .bucket(BUCKET_NAME)
                            .config(config)
                    .build());
        }



        return minioClient;
    }


}
